package com.yexx.starter.optms.idempotent.keygen.impl;

import com.yexx.starter.optms.idempotent.annotation.Idempotent;
import com.yexx.starter.optms.idempotent.keygen.LockKeyGenerator;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description: 默认的锁生成规则
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date 2022/06/01:22:42
 */
public class DefaultLockKeyResolver implements LockKeyGenerator {

    private final HeaderLockKeyResolver headerLockKeyResolver;

    private final SessionIdLockKeyResolver sessionIdLockKeyResolver;

    private final CookieLockKeyResolver cookieLockKeyResolver;

    public DefaultLockKeyResolver(HeaderLockKeyResolver headerLockKeyResolver,
                                  SessionIdLockKeyResolver sessionIdLockKeyResolver,
                                  CookieLockKeyResolver cookieLockKeyResolver) {
        this.headerLockKeyResolver = headerLockKeyResolver;
        this.sessionIdLockKeyResolver = sessionIdLockKeyResolver;
        this.cookieLockKeyResolver = cookieLockKeyResolver;
    }

    @Override
    public String resolver(Idempotent idempotent, HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) {

        //header
        String lockKey = headerLockKeyResolver.resolver(idempotent, request, response, handlerMethod);
        if (!lockKey.contains(NOT_FOUND)) {
            return lockKey;
        }

        //cookie
        lockKey = cookieLockKeyResolver.resolver(idempotent, request, response, handlerMethod);
        if (!lockKey.contains(NOT_FOUND)) {
            return lockKey;
        }

        // sessionId
        lockKey = sessionIdLockKeyResolver.resolver(idempotent, request, response, handlerMethod);
        return lockKey;
    }
}
